<template>
	<view class="leave-container">

		<view class="form-section">
			<view class="form-item">
				<text class="form-label">关联项目 <text class="required">*</text></text>
				<picker @change="onProjectChange" :value="projectIndex" :range="projectList">
					<view class="picker-input">
						<text>{{ projectList[projectIndex] }}</text>
						<text class="picker-arrow">></text>
					</view>
				</picker>
			</view>
		</view>
		<view class="form-section">
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">请假类型</text>
					<picker @change="onLeaveTypeChange" :value="leaveTypeIndex" :range="leaveTypes" :disabled="isEdit">
						<view class="picker-input">
							<text>{{ leaveTypes[leaveTypeIndex] }}</text>
							<text class="picker-arrow" v-if="!isEdit">></text>
						</view>
					</picker>
				</view>
			</view>



			<view class="form-item">
				<text class="form-label">开始时间</text>
				<DateTimePicker v-model="startTime" :disabled="isEdit" />
			</view>

			<view class="form-item">
				<text class="form-label">结束时间</text>
				<DateTimePicker v-model="endTime" :disabled="isEdit" />
			</view>

			<view class="form-item">
				<text class="form-label">请假时长</text>
				<text class="duration-text">{{ formatDuration() }}</text>
			</view>

			<view class="form-item textarea-item">
				<text class="form-label">请假事由</text>
				<textarea class="form-textarea" v-model="leaveReason" placeholder="请详细说明请假事由" maxlength="200"
					:disabled="isEdit"></textarea>
				<text class="char-count">{{ leaveReason.length }}/200</text>
			</view>

			<view class="form-item">
				<UploadAttachments 
					style="width: 100%;"
					v-model="uploadedFiles"
					label="说明附件"
					:disabled="isEdit"
					:max-count="5"
					:file-types="['jpg', 'jpeg', 'png']"
				/>
			</view>
		</view>

		<!-- 审批流程 -->
		<view class="approval-section">
			<text class="section-title">审批流程</text>
			<view class="approval-steps">
				<view v-if="approvalSteps.length > 0">
					<view class="approval-step" v-for="(step, index) in approvalSteps" :key="index">
						<view class="step-header">
							<view class="step-avatar">
								<text class="avatar-text">{{ step.user_name.charAt(0) }}</text>
							</view>
							<view class="step-info">
								<text class="step-name">{{ step.user_name }}</text>
								<text class="step-position">{{ step.position }}</text>
							</view>
							<text v-if="!isNew" :class="['step-status', getStepStatusClass(step.status)]">
								{{ getStepStatusText(step.status) }}
							</text>
						</view>
						<view class="step-content" v-if="step.comment">
							<text class="step-comment">{{ step.comment }}</text>
							<text class="step-time">{{ step.update_time }}</text>
						</view>
					</view>
				</view>
				<view v-else class="empty-approval">
					<view class="empty-icon">!</view>
					<text class="empty-text">请假流程未定义，请联系管理员</text>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<button v-if="!isEdit" class="submit-button" @tap="submitLeave" :disabled="!canSubmit()">
				{{ approvalSteps.length > 0 ? '提交' : '请假流程未定义，无法提交' }}
			</button>
			<button class="cancel-button" @tap="cancelLeave" v-if="isEdit && canCancel()">
				作废申请
			</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import calculateLeaveTimeWithType from '@/common/calculateLeaveTimeWithType'
import DateTimePicker from '@/components/DateTimePicker.vue'
import UploadAttachments from '@/components/UploadAttachments.vue'
import { leaveApi } from '@/common/api'
import { getProjects, getCurrentToken } from '@/common/auth'
import config from '@/common/config'
import { uploadFile as uploadSingleFile, uploadAttachments, formatFileSize } from '@/common/upload'

// TypeScript interfaces
interface LeaveFile {
	name: string
	url: string
	path: string
	size: string
	type: string
}

interface LeaveDuration {
	days: number
	hours: number
	totalHours?: number
}

interface ApprovalStep {
	position: string
	user_name: string
	user_id: string
	status: string
	comment?: string
	update_time?: string
}

interface Project {
	project_id: string
	project_name: string
}

const leaveTypes = ref<string[]>(['事假', '病假', '年假', '调休', '婚假', '产假', '丧假'])
const leaveTypeIndex = ref<number>(0)
const startTime = ref<string>('')
const endTime = ref<string>('')
const leaveReason = ref<string>('')
const uploadedFiles = ref<LeaveFile[]>([])
const timeError = ref<boolean>(false)
const leaveDuration = ref<LeaveDuration>({
	days: 0,
	hours: 0
})

const projects = getProjects() as Project[]
const projectIndex = ref<number>(0)
const projectList = ref<string[]>(projects.map((project) => project.project_name))
const workflow_id = ref<number>(0)
const region_company = ref<string>('')

// 是否为编辑/查看模式
const isEdit = ref<boolean>(false)
const leaveId = ref<string>('')
const isNew = ref<boolean>(true)

// 请假类型映射
const leaveTypeMap: Record<string, string> = {
	'事假': 'personal',
	'病假': 'sick',
	'年假': 'annual',
	'调休': 'personal',
	'婚假': 'marriage',
	'产假': 'maternity',
	'丧假': 'bereavement'
}

const approvalSteps = ref<ApprovalStep[]>([])

// 获取步骤状态样式
const getStepStatusClass = (status: string): string => {
	const statusMap: Record<string, string> = {
		'pending': 'pending',
		'approved': 'approved',
		'rejected': 'rejected',
		'canceled': 'canceled'
	}
	return statusMap[status] || 'pending'
}

// 获取步骤状态文本
const getStepStatusText = (status: string): string => {
	const statusMap: Record<string, string> = {
		'pending': '待审批',
		'approved': '已通过',
		'rejected': '已拒绝',
		'canceled': '已取消'
	}
	return statusMap[status] || '待审批'
}

const onLeaveTypeChange = (e: any) => {
	leaveTypeIndex.value = e.detail.value
}

const onProjectChange = (e: any) => {
	projectIndex.value = e.detail.value
}

// 加载请假详情
const loadLeaveDetail = async (id: string) => {
	try {
		uni.showLoading({
			title: '加载中...'
		})

		const res = await leaveApi.getDetail(id)
		if (res.success && res.data) {
			const detail = res.data

			// 设置请假类型
			const typeIndex = leaveTypes.value.findIndex(type =>
				leaveTypeMap[type] === detail.leaveType
			)
			if (typeIndex !== -1) {
				leaveTypeIndex.value = typeIndex
			}

			// 设置时间
			startTime.value = detail.startTime
			endTime.value = detail.endTime
			leaveReason.value = detail.reason

			// 设置附件
			if (detail.attachments && detail.attachments.length > 0) {
				uploadedFiles.value = detail.attachments.map((file: any) => {
					return ({
						name: file.file_name,
						url: file.url,
						size: formatFileSize(file.file_size),
						type: file.file_type
					})
				})
			}

			// 设置审批流程
			if (detail.approval_steps) {
				approvalSteps.value = detail.approval_steps
			}
			// 计算请假时长
			calculateLeaveDuration()

			projectIndex.value = projects.findIndex((project) => project.project_id === detail.project_id)
			let approval_process = detail.approval_process;
			workflow_id.value = detail.workflow_id;
			region_company.value = detail.region_company;
			// uploadedFiles.value = detail.attachments.map((file: any) => ({
			// 	name: file.name,
			// 	url: config.baseUrl + file.url,
			// 	path: file.path,
			// 	size: file.size,
			// 	type: file.type
			// }))
			approvalSteps.value = approval_process.map((process: any) => {
				const { records, approver } = process;
				let status = 'pending';
				if (records && records.length > 0) {
					const lastRecord = records[records.length - 1];
					status = lastRecord.action;
				}
				return ({
					position: approver.position || '审批人',
					user_name: approver.name,
					status: status,
					user_id: approver.uid
				})
			});
			return detail;
		} else {
			uni.showToast({
				title: '加载详情失败',
				icon: 'none'
			})
			return null;
		}
	} catch (error) {
		console.error('加载请假详情失败:', error)
		uni.showToast({
			title: '加载详情失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 计算请假时长
const calculateLeaveDuration = () => {
	if (!startTime.value || !endTime.value) {
		leaveDuration.value = {
			days: 0,
			hours: 0,
			totalHours: 0
		}
		return
	}

	try {
		const startDate = new Date(startTime.value)
		const endDate = new Date(endTime.value)
		if (startDate >= endDate) {
			leaveDuration.value = {
				days: 0,
				hours: 0,
				totalHours: 0
			}
			return
		}

		const currentLeaveType = leaveTypeMap[leaveTypes.value[leaveTypeIndex.value]] || 'personal'
		const result = calculateLeaveTimeWithType({
			startTime: startDate,
			endTime: endDate,
			leaveType: currentLeaveType,
			workDays: [1, 2, 3, 4, 5],
			holidays: [],
			hoursPerDay: 8
		})

		leaveDuration.value = {
			days: result.days || 0,
			hours: result.hours || 0,
			totalHours: result.hours || 0
		}
	} catch (error) {
		console.error('计算请假时间出错:', error)
		leaveDuration.value = {
			days: 0,
			hours: 0,
			totalHours: 0
		}
	}
}

// 监听时间变化
watch([startTime, endTime], () => {
	calculateLeaveDuration()
})

// 页面加载
onLoad(async (options) => {
	if (options.id) {
		leaveId.value = options.id
		isEdit.value = true
		isNew.value = false
		const detail = await loadLeaveDetail(options.id)
	} else {
		isEdit.value = false
		isNew.value = true
		// 新增模式，加载审批人
		loadApprovers()
	}
})



const addApprover = () => {
	// 添加审批人逻辑
	console.log('添加审批人')
}

const canSubmit = (): boolean => {
	return !!startTime.value && !!endTime.value && leaveDuration.value.hours > 0 && !timeError.value && approvalSteps.value.length > 0
}

const submitLeave = async () => {
	if (!canSubmit()) {
		uni.showToast({
			title: '请完善申请信息',
			icon: 'none'
		})
		return
	}

	uni.showLoading({
		title: '提交中...'
	})

	try {
		// 准备提交的数据（先不包含附件）
		const submitData = {
			leaveType: leaveTypes.value[leaveTypeIndex.value],
			startTime: new Date(startTime.value).toISOString(),
			endTime: new Date(endTime.value).toISOString(),
			hours: leaveDuration.value.hours,
			reason: leaveReason.value,
			submitTime: new Date().toISOString(),
			region_company: region_company.value,
			workflow_id: workflow_id.value,
			project_id: projects[projectIndex.value].project_id
		}

		console.log('提交的请假数据:', submitData)

		uni.showLoading({
			title: '提交申请中...'
		})

		// 先提交表单数据
		const res = await leaveApi.apply(submitData)

		if (!res.success) {
			uni.hideLoading()
			uni.showToast({
				title: res.message || '提交失败',
				icon: 'none',
				duration: 3000
			})
			return
		}

		// 获取申请ID
		const { leave_id, approval_instance_id } = res.data

		// 如果有附件，再上传附件
		if (uploadedFiles.value.length > 0) {
			uni.showLoading({
				title: '上传附件中...'
			})

			try {
				// 转换文件格式
				const files = uploadedFiles.value.map(file => ({
					path: file.path,
					name: file.name,
					size: parseInt(file.size) || 0,
					type: file.type
				}));

				// 使用通用上传工具上传文件，支持并行上传
				const uploadedAttachments = await uploadAttachments(				
					files,
					true, // 并行上传
					{
						type: "attachment",
						relation_id: leave_id, // 传递申请ID
						approval_instance_id: approval_instance_id, // 传递审批实例ID
						relation_type: "leave" // 传递申请类型
					},
					(current, total) => {
						// 更新上传进度
						uni.showLoading({
							title: `上传中 ${current}/${total}`
						});
					}
				);

				// 如果需要，可以调用更新附件API
				if (uploadedAttachments.length > 0) {
					const attachments = uploadedAttachments.map(file => ({
						path: file.path,
						size: String(file.size),
						type: file.type,
						url: file.url
					}));

					// 可选：调用更新附件API
					// await leaveApi.updateAttachments(leaveApplicationId, attachments);
				}
			} catch (error: any) {
				console.error('文件上传失败:', error)
				uni.showToast({
					title: '部分附件上传失败，请在详情页重新上传',
					icon: 'none',
					duration: 2000
				})
				// 继续流程，不影响已提交的申请
			}
		}

		uni.hideLoading()
		console.log('提交成功:', res)

		uni.showToast({
			title: '申请提交成功',
			icon: 'success'
		})

		// 清空表单
		leaveReason.value = ''
		uploadedFiles.value = []
		leaveTypeIndex.value = 0
		startTime.value = ''
		endTime.value = ''

		// 跳转到首页
		uni.switchTab({
			url: '/pages/home/home'
		})
	} catch (error: any) {
		uni.hideLoading()
		console.error('提交失败:', error)
		uni.showToast({
			title: error.message || '网络错误，请稍后重试',
			icon: 'none',
			duration: 3000
		})
	}
}

const formatDuration = (): string => {
	try {
		return `${leaveDuration.value.hours}小时 `

	} catch (error) {
		console.error('格式化请假时间出错:', error)
		return '0 天'
	}
}


// 加载审批人列表
const loadApprovers = async () => {
	try {
		if (projects[projectIndex.value]) {
			uni.showLoading({
				title: '加载审批人...'
			})
			const projectId = projects[projectIndex.value].project_id;
			const res = await leaveApi.getApprovers(projectId, "leave");
			uni.hideLoading()

			if (res.success && res.data.length > 0) {
				const approvalWorkflow = res.data[0];
				workflow_id.value = approvalWorkflow.id;
				region_company.value = approvalWorkflow.region_company;
				approvalSteps.value = approvalWorkflow.approval_process.map((approver: any) => ({
					position: approver.approver_position || '审批人',
					user_name: approver.approver_name,
					user_id: approver.approver_id
				}))
				console.log('审批人列表加载成功:', approvalSteps.value)
			} else {
				console.log('使用默认审批人列表')
				// 保持默认的审批人列表
			}
		}
	} catch (error) {
		uni.hideLoading()
		console.error('获取审批人列表失败:', error)

		// 显示错误提示，但不影响页面使用
		uni.showToast({
			title: '获取审批人失败，使用默认配置',
			icon: 'none',
			duration: 2000
		})

		// 保持默认的审批人列表
	}
}

// 判断是否可以作废
const canCancel = (): boolean => {
	if (isNew.value) {
		return false
	}
	// 只有待审批状态的请假申请才能作废
	return approvalSteps.value.length > 0 &&
		approvalSteps.value[0].status === 'pending'
}

// 作废请假申请
const cancelLeave = async () => {
	try {
		uni.showModal({
			title: '确认作废',
			content: '确定要作废该请假申请吗？',
			success: async (res: { confirm: boolean }) => {
				if (res.confirm) {
					uni.showLoading({
						title: '处理中...'
					})

					const res = await leaveApi.cancel(leaveId.value)
					uni.hideLoading()

					if (res.success) {
						uni.showToast({
							title: '作废成功',
							icon: 'success'
						})

						uni.switchTab({
							url: '/pages/home/home'
						})

						// 刷新页面数据
						//await loadLeaveDetail(leaveId.value)
					} else {
						uni.showToast({
							title: res.message || '作废失败',
							icon: 'none'
						})
					}
				}
			}
		})
	} catch (error: any) {
		uni.hideLoading()
		console.error('作废失败:', error)
		uni.showToast({
			title: error.message || '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}
</script>

<style scoped>
.leave-container {
	padding: 0;
	background-color: #f5f6fa;
	min-height: 100vh;
}

.form-section {
	background: white;
	border-radius: 0;
	padding: 0;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.form-title {
	font-size: 40rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 32rpx;
	display: block;
}

.form-item {
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
	margin-bottom: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	min-height: 88rpx;
}

.form-item:last-child {
	border-bottom: none;
}

.form-item.textarea-item {
	flex-direction: column;
	align-items: stretch;
	min-height: auto;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 0;
	display: block;
	flex-shrink: 0;
}

.required {
	color: #f44336;
	font-size: 28rpx;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	min-height: 48rpx;
	flex: 1;
	max-width: 400rpx;
}

.picker-arrow {
	color: #999;
	margin-left: 8rpx;
}

.picker-text {
	font-size: 28rpx;
	color: #333;
	text-align: right;
	flex: 1;
}

.picker-text.placeholder {
	color: #999;
}

.duration-display {
	display: flex;
	align-items: baseline;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	justify-content: flex-end;
}

.duration-number {
	font-size: 28rpx;
	font-weight: normal;
	color: #333;
	margin-right: 0;
}

.days-unit {
	font-size: 28rpx;
	color: #666;
}

.form-textarea {
	width: 100%;
	box-sizing: border-box;
	min-height: 120rpx;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	font-size: 28rpx;
	line-height: 1.5;
	margin-top: 16rpx;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
	display: block;
}



.approval-section {
	background: white;
	border-radius: 0;
	padding: 32rpx;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.approval-note {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 24rpx;
	display: block;
}

.approver-section {
	margin-bottom: 0;
}

.approver-header {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.approver-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 12rpx;
	background: #ddd;
	border-radius: 6rpx;
}

.approver-label {
	font-size: 28rpx;
	color: #333;
}

.approver-list {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.approver-item {
	display: flex;
	align-items: center;
	padding: 16rpx;
	background: #f8f9fa;
	border-radius: 12rpx;
	gap: 16rpx;
}

.approver-avatar {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #2B5BA1;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
	flex-shrink: 0;
}

.avatar-text {
	color: white;
}

.approver-info {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
	flex: 1;
}

.approver-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.approver-title {
	font-size: 24rpx;
	color: #666;
}

.add-approver {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	border: 2rpx dashed #ccc;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-left: 16rpx;
}

.add-icon {
	font-size: 32rpx;
	color: #999;
}

.submit-section {
	padding: 32rpx;
	margin-bottom: 0;
}

.submit-button {
	width: 100%;
	background: #2B5BA1;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 6rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.submit-button[disabled] {
	background: #ccc;
}

:deep(.error .picker-input) {
	border-color: #f44336;
	background-color: #fff5f5;
}

:deep(.picker-input) {
	border: none !important;
	background: transparent !important;
	padding: 0 !important;
	justify-content: flex-end !important;
	max-width: 400rpx;
}

:deep(.picker-text) {
	text-align: right !important;
	color: #333 !important;
}

:deep(.picker-text.placeholder) {
	color: #999 !important;
}

:deep(.picker-arrow) {
	margin-left: 8rpx !important;
}

.approval-steps {
	margin-top: 24rpx;
}

.approval-step {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
}

.step-header {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.step-avatar {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #2B5BA1;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
	margin-right: 16rpx;
}

.step-info {
	flex: 1;
}

.step-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
}

.step-position {
	font-size: 24rpx;
	color: #666;
}

.step-status {
	font-size: 24rpx;
	padding: 4rpx 12rpx;
	border-radius: 8rpx;
}

.step-status.pending {
	color: #2196f3;
	background: #e3f2fd;
}

.step-status.approved {
	color: #4caf50;
	background: #e8f5e9;
}

.step-status.rejected {
	color: #f44336;
	background: #ffebee;
}

.step-status.canceled {
	color: #9e9e9e;
	background: #f5f5f5;
}

.step-content {
	margin-top: 16rpx;
	padding-top: 16rpx;
	border-top: 1rpx solid #eee;
}

.step-comment {
	font-size: 28rpx;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.step-time {
	font-size: 24rpx;
	color: #999;
}

.duration-text {
	font-size: 28rpx;
	color: #333;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.picker-arrow {
	color: #999;
	margin-left: 8rpx;
}

.cancel-button {
	width: 100%;
	background: #f44336;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 6rpx;
	font-size: 32rpx;
	font-weight: 500;
	margin-top: 16rpx;
}

.cancel-button[disabled] {
	background: #ccc;
}

.empty-approval {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 40rpx 24rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	text-align: center;
}

.empty-icon {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #ff9800;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 16rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #666;
}
</style>